package cn.itcast.bos.web.action.common;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.springframework.data.domain.Page;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: SOS
 * @Create: 2018-02-01 18:38
 */

/**
 * 提取出一个公共的方法,
 * @param <T>
 */
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>{

    //模型驱动
    protected T model ;

    @Override
    public T getModel() {
        return model;
    }

    //构造器完成model的实例化
    public BaseAction(){
        //构造子类Action对象,获取继承父类的泛型
        //AreaAction extends BaseAction<Area>
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        //获取类型的第一个泛型参数
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Class<T> modelclass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        try {
            model = modelclass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //接受分页查询的page和rows
    protected Integer page;
    protected Integer rows;

    public void setPage(Integer page) {
        this.page = page;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public void pushPageDataToValueStack(Page<T> pageData){
        Map<String ,Object> map = new HashMap<>();
        map.put("total",pageData.getTotalElements());
        map.put("rows",pageData.getContent());
        ActionContext.getContext().getValueStack().push(map);
    }
}
